<template>
  <div class="app-container">
    <div class="nav">
      <el-button
        type="primary"
        plain
        size="small"
        icon="el-icon-setting"
        @click="handleSetting"
        >设置</el-button
      >
    </div>
    <el-table   v-loading="loading" :data="tableData" stripe style="width: 100%" >
      <el-table-column prop="level" label="级别"> </el-table-column>
      <el-table-column prop="levelName" label="等级名称"> </el-table-column>
      <el-table-column prop="desiredGrowthValue" label="所需成长值">
      </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button @click="handleClick(scope)" type="text">编辑</el-button>
          <el-button @click="onQr(scope)" type="text">会员等级二维码</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="1"
      :page-sizes="[5]"
      :page-size="5"
      layout="->,total, sizes, prev, pager, next, jumper"
      :total="total"
      class="container-pagination"
    >
    </el-pagination>
    <el-dialog
      title="编辑"
      :visible.sync="dialogVisible"
      width="45%"
      :before-close="handleClose"
      class="container-dialog"
    >
      <el-form :model="form" :rules="rules" ref="ruleForm">
        <el-row :gutter="25">
          <el-col :span="12">
            <el-form-item label="等级名称">
              <el-input
                v-model="form.levelName"
                maxlength="5"
                show-word-limit
                :disabled="true"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所需成长值" prop="desiredGrowthValue">
              <el-input
                type="text"
                class="control-amountPayable"
                v-model="form.desiredGrowthValue"
                maxlength="22"
                show-word-limit
                onkeyup="value=value.replace(/[^\d]/g,'')"
                @input="inputAmountPayable"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancellation">取 消</el-button>
        <el-button type="primary" @click="determinate('ruleForm')">
          确 定</el-button
        >
      </span>
    </el-dialog>
    <!-- 设置弹窗 -->
    <el-drawer
      size="55%"
      title="成长值设置"
      :visible.sync="settingDrawer"
      :before-close="closeSetting"
    >
      <el-form
        class="setting_form"
        ref="settingForm"
        :model="settingForm"
        :rules="settingRules"
      >
        <el-form-item label="" prop="expireMode">
          <div class="title">成长值有效期设置</div>
          <el-radio-group
            v-model="settingForm.expireMode"
            style="margin-left: 0.1rem"
          >
            <el-radio :label="1">永久有效</el-radio>
            <el-radio :label="2">按月清零</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item prop="dayOfMonth" v-if="settingForm.expireMode == 2">
          <div class="title">月时间清零选中</div>
          <div style="display: inline-block">
            <el-radio-group v-model="settingForm.dayOfMonth" size="medium">
              <el-radio-button
                v-for="day in daysOfMonth"
                :label="day"
                :key="day"
                >{{ day }}</el-radio-button
              >
            </el-radio-group>
            <el-radio-group v-model="settingForm.dayOfMonth" size="medium">
              <el-radio-button
                v-for="day in daysOfMonth2"
                :label="day"
                :key="day"
                >{{ day }}</el-radio-button
              >
            </el-radio-group>
          </div>

          <div v-show="settingForm.expireMode == 2" style="display: flex">
            <template>
              <el-time-select
                placeholder="请选择时间点"
                value-format="HH"
                v-model="settingForm.timeOfDay"
                size="small"
                :picker-options="{
                  start: '00:00',
                  step: '01:00',
                  end: '23:00',
                }"
              >
              </el-time-select>
            </template>
          </div>
        </el-form-item>
      </el-form>
      <div class="footer">
        <el-button @click="closeSetting">取 消</el-button>
        <el-button type="primary" @click="settingSubmit">保 存</el-button>
      </div>
    </el-drawer>
    <el-dialog title="导出二维码" center  :visible.sync="dialogQr" width="45%"  @close="onCancel">
      <div class="qr_content">
        <div class="Vip_grade">
          <p>会员等级：{{vipName}}</p>
          <div>
            <el-radio v-model="radio" label="1">固定天数</el-radio>
            <el-radio v-model="radio" label="2">固定时间段</el-radio>
          </div>
          <div class="input_day" v-if="radio==1">
            <!-- <span>自用户扫码后 <el-input  v-model="input"  placeholder="天数"  min=" 0"  type="number"></el-input> 天内生效</span> -->
            <span>自用户扫码后<el-input-number v-model="input"  :min="0" name="number" @change="handleChange" ></el-input-number>天内生效</span>
          </div>
          <div v-else>
            <div class="block">
              <el-date-picker class="time_picker" v-model="dataPicker" type="daterange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" value-format="yyyy-MM-dd"/>
               <el-time-picker class="time_picker" is-range v-model="timePicker" range-separator="至" start-placeholder="开始时间" end-placeholder="结束时间" placeholder="选择时间范围" value-format="HH:mm:ss"/>
            </div>

          </div>
        </div>
        <div class="qr_code">
          <div v-loading="loading2" v-if="expireMode" element-loading-spinner="el-icon-loading">
            <vipQr v-if="qrLoading" :qrUrl="qrCodeUrl" id="vip_qr"/>
          </div>
          <div v-else class="empty">
            请点击按钮生成新二维码
          </div>
          <div class="acton_btn">
            <button  @click="handleQrCode(1)">生成新二维码</button>
            <button @click="handleQrCode(2)">导出二维码</button>
          </div>
        </div>
      </div>
      <div class="tip">说明:扫码后可直接加入该会员等级</div>
      <span slot="footer" class="dialog-footer">
        <!-- <el-button @click="onCancel">取 消</el-button>
        <el-button type="primary" @click="dialogQr = false">确 定</el-button> -->
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { formatDate } from "@/utils/index.js";
import { getGrade, upGrade, setGrade, saveGradeLevel,getGradeQr,saveGrade } from "@/api/grade";
import vipQr from "@/components/QrCode/VipGrade-qr.vue";
import html2canvas from "html2canvas";
export default {
  name: "Dept",
  data() {
    const validateDays = (rule, value, callback) => {
      if (!this.settingForm.dayOfMonth) {
        return callback(new Error("请选择月时间"));
      } else if (!this.settingForm.timeOfDay) {
        return callback(new Error("请选择时间点"));
      }
      callback();
    };
    const validatePass = (rule, value, callback) => {
      if (this.form.desiredGrowthValue) {
        const pureNumber = /^[0-9]*$/; //正则表达式
        if (pureNumber.test(this.form.desiredGrowthValue)) {
          if (this.maximum && this.minimum) {
            if (
              this.maximum.desiredGrowthValue > this.form.desiredGrowthValue &&
              this.form.desiredGrowthValue > this.minimum.desiredGrowthValue
            ) {
              callback();
            } else {
              callback(
                new Error(
                  `成长值为${this.minimum.desiredGrowthValue} - ${this.maximum.desiredGrowthValue}`
                )
              );
            }
          } else {
            if (this.minimum) {
              if (
                this.minimum.desiredGrowthValue < this.form.desiredGrowthValue
              ) {
                callback();
              } else {
                callback(
                  new Error(`成长值不能小于${this.minimum.desiredGrowthValue}`)
                );
              }
            } else if (this.maximum) {
              if (
                this.maximum.desiredGrowthValue > this.form.desiredGrowthValue
              ) {
                callback();
              } else {
                callback(
                  new Error(`成长值不能大于${this.maximum.desiredGrowthValue}`)
                );
              }
            }
          }
          // 输入正确
        } else {
          // 输入带字母
          const desiredGrowthValue = this.form.desiredGrowthValue.slice(
            0,
            this.form.desiredGrowthValue.length - 1
          );

          if (this.maximum && this.minimum) {
            if (
              this.maximum.desiredGrowthValue > desiredGrowthValue &&
              desiredGrowthValue > this.minimum.desiredGrowthValue
            ) {
              callback();
            } else {
              callback(
                new Error(
                  `成长值为${this.minimum.desiredGrowthValue} - ${this.maximum.desiredGrowthValue}`
                )
              );
            }
          } else {
            if (this.minimum) {
              if (
                this.minimum.desiredGrowthValue < this.form.desiredGrowthValue
              ) {
                callback();
              } else {
                callback(
                  new Error(`成长值不能小于${this.minimum.desiredGrowthValue}`)
                );
              }
            } else if (this.maximum) {
              if (
                this.maximum.desiredGrowthValue > this.form.desiredGrowthValue
              ) {
                callback();
              } else {
                callback(
                  new Error(`成长值不能大于${this.maximum.desiredGrowthValue}`)
                );
              }
            }
          }
        }
      } else {
        callback(new Error("请输入所需成长值"));
      }
    };
    return {
      daysOfMonth: [
        "1",
        "2",
        "3",
        "4",
        "5",
        "6",
        "7",
        "8",
        "9",
        "10",
        "11",
        "12",
        "13",
        "14",
        "15",
        "16",
      ],
      daysOfMonth2: [
        "17",
        "18",
        "19",
        "20",
        "21",
        "22",
        "23",
        "24",
        "25",
        "26",
        "27",
        "28",
        "29",
        "30",
        "31",
      ],
      settingDrawer: false,
      currForm: {},
      settingForm: {
        expireMode: 1,
        dayOfMonth: "",
        timeOfDay: "",
      },
      settingRules: {
        expireMode: [
          { required: true, message: "请选择有效期设置", trigger: "blur" },
        ],
        dayOfMonth: [{ validator: validateDays, trigger: "change" }],
      },
      row: null,
      total: null,
      maximum: 0,
      minimum: 0,
      form: {
        levelName: "",
        desiredGrowthValue: "",
      },
      dialogVisible: false,
      tableData: [
        {
          level: "一级",
          levelName: "普卡",
          desiredGrowthValue: 0,
        },
        {
          level: "二级",
          levelName: "银卡",
          desiredGrowthValue: 88,
        },
        {
          level: "三级",
          levelName: "金卡",
          desiredGrowthValue: 888,
        },
        {
          level: "四级",
          levelName: "钻卡",
          desiredGrowthValue: 8888,
        },
        {
          level: "五级",
          levelName: "黑卡",
          desiredGrowthValue: 88888,
        },
      ],
      rules: {
        desiredGrowthValue: [
          { required: true, validator: validatePass, trigger: "blur" },
        ],
      },
      dialogQr: false,
      radio: '1',
      input: "",
      dataPicker:'',//日期
      timePicker:'',//时间
      qrCodeUrl:'',
      qrLoading:false,
      loading:false,
      gradeCode:null,
      vipName:'',
      loading2:false,
      expireMode:null

    };
  },
  components:{
    vipQr
  },
  created() {
    this.getGrade();
    this.getGradeData();
  },
  methods: {
    handleChange(value) {
      // 使用正则表达式校验输入是否为整数
      const regex = /^\d*$/;
      if (regex.test(value)) {
        // 如果是整数，则更新数据
        this.input = parseInt(value, 10);
      } else {
        this.$message.warning('请输入大于0的整数')
        // 如果不是整数，可以进行其他处理，比如清空输入
        this.input = 0;
        
      }
      console.log(this.input);
    },
    // 获取会员等级设置数据
    async getGradeData() {
      const res = await setGrade();
      this.settingForm = res.data;
      if (!this.settingForm.expireMode) this.settingForm.expireMode = 1;
      if (this.settingForm.timeOfDay) {
        this.settingForm.timeOfDay = this.settingForm.timeOfDay.substring(
          0, this.settingForm.timeOfDay.length - 3
        );
      }
      this.currForm = JSON.parse(JSON.stringify(this.settingForm));
    },
    // 提交设置抽屉
    async settingSubmit() {
      await this.$refs["settingForm"].validate();
      if (this.settingForm.timeOfDay) {
        this.settingForm.timeOfDay = this.settingForm.timeOfDay + ":00";
      }
      const res = await saveGradeLevel(this.settingForm);
      this.$message.success(res.msg);
      this.settingDrawer = false;
      this.getGradeData();
    },
    // 关闭抽屉
    async closeSetting() {
      await this.$refs["settingForm"].clearValidate();
      this.settingDrawer = false;
    },
    // 设置
    handleSetting() {
      this.settingForm = JSON.parse(JSON.stringify(this.currForm));
      this.settingDrawer = true;
    },
    async onQr(scope){
      this.vipName=scope.row.levelName
      const gradeCode=scope.row.gradeCode
      this.gradeCode=gradeCode
      const res=await getGradeQr({gradeCode})
      if(res&&res.code==200){
        this.radio=res.data.expireMode?String(res.data.expireMode):'1'
        this.expireMode=res.data.expireMode
        this.input=res.data.fixedDay
        this.dialogQr=true
        this.dataPicker=[ `${res.data.effectStartDate}`, `${res.data.effectEndDate}`]
        this.timePicker=[ `${res.data.effectStartTime}`, `${res.data.effectEndTime}`]
        if(res.data.expireMode){
          console.log(window.location.origin);
          let url = window.location.origin;
          let baseURL = "";
          switch (url) {
            case "https://yftx.xailife.com":
              baseURL =`https://yftx-map.xailife.com/${this.presentEnterprise.enterpriseId}/my?version=${res.data.version}&gradeCode=${res.data.gradeCode}`;
              break;
            case "https://yftx-test.xailife.com":
              baseURL =`https://yftx-map-test.xailife.com/${this.presentEnterprise.enterpriseId}/my?version=${res.data.version}&gradeCode=${res.data.gradeCode}`;
              break;
            case "https://yftx-dev.xailife.com":
              baseURL =`https://yftx-map-dev.xailife.com/${this.presentEnterprise.enterpriseId}/my?version=${res.data.version}&gradeCode=${res.data.gradeCode}`;
              break;
            default:
              baseURL=`https://yftx-map-dev.xailife.com/${this.presentEnterprise.enterpriseId}/my?version=${res.data.version}&gradeCode=${res.data.gradeCode}`
              break;}
          // const url= process.env.VUE_APP_BASE_API+ `/${this.presentEnterprise.enterpriseId}/my?version=${res.data.version}&gradeCode=${res.data.gradeCode}`
          // url.replace('/prod-api', '')
          // this.qrCodeUrl= `https://yftx-map-dev.xailife.com/174/my?version=${res.data.version}&gradeCode=${res.data.gradeCode}`
          console.log(baseURL);
          this.qrCodeUrl=baseURL
          this.qrLoading=true
        }
      }else{
        this.$message.error(res&&res.msg)
      }

    },
    handleQrCode(type){
       switch (type){
        case 1:
          let params={
            expireMode:this.radio||null,
            gradeCode:this.gradeCode||null,
            enterpriseId:this.presentEnterprise.enterpriseId
          }
          if(this.radio==1){
            params['fixedDay']=this.input||null
            if(this.input){
              this.onSave(params)
            }else{
              this.$message.warning('请输入固定天数')
            }
          }else if(this.radio==2){
            if(this.dataPicker&&this.timePicker){
              params['effectStartDate']=this.dataPicker[0]
              params['effectEndDate']=this.dataPicker[1]
              params['effectStartTime']=this.timePicker[0]
              params['effectEndTime']=this.timePicker[1]
              if(params['effectStartDate']&&params['effectStartDate']!='null'&&params['effectEndDate']&&params['effectEndDate']!='null'&&params['effectStartTime']&&params['effectStartTime']!='null'&&params['effectEndTime']&&params['effectEndTime']!='null'){ 
                 this.onSave(params)
              }else{
                this.$message.warning('请选择日期和时间')
              }
            }else{
              this.$message.warning('请选择日期和时间')
            }
          }
          this.qrLoading=true
          break
        case 2:
            // 创建一个虚拟的链接元素
         html2canvas(document.getElementById("vip_qr"), {
            allowTaint: false,
          }).then((canvas) => {
            const a = document.createElement("a");
            const event = new MouseEvent("click");
            a.download = '会员等级二维码'; // 设置下载的文件名
            a.href = canvas.toDataURL("image/png"); // 设置 Canvas 数据URL
            a.dispatchEvent(event);
          });
          break;
      }
    },
    async onSave(params){
      this.loading2=true
      const res=await saveGrade(params)
      if(res&&res.code==200){
        this.qrLoading=true
        this.expireMode=res.data.expireMode
        let url = window.location.origin;
          let baseURL = "";
           switch (url) {
            case "https://yftx.xailife.com":
              baseURL =`https://yftx-map.xailife.com/${this.presentEnterprise.enterpriseId}/my?version=${res.data.version}&gradeCode=${res.data.gradeCode}`;
              break;
            case "https://yftx-test.xailife.com":
              baseURL =`https://yftx-map-test.xailife.com/${this.presentEnterprise.enterpriseId}/my?version=${res.data.version}&gradeCode=${res.data.gradeCode}`;
              break;
            case "https://yftx-dev.xailife.com":
              baseURL =`https://yftx-map-dev.xailife.com/${this.presentEnterprise.enterpriseId}/my?version=${res.data.version}&gradeCode=${res.data.gradeCode}`;
              break;
            default:
              break;}
        // const url= process.env.VUE_APP_BASE_API+ `/${this.presentEnterprise.enterpriseId}/my?version=${res.data.version}&gradeCode=${res.data.gradeCode}`
        // url.replace('/prod-api', '')
        // this.qrCodeUrl= `https://yftx-map-dev.xailife.com/174/my?version=${res.data.version}&gradeCode=${res.data.gradeCode}`
        this.qrCodeUrl=baseURL
        console.log('二维码链接',this.qrCodeUrl);
        setTimeout(() => {
          this.loading2=false
        }, 500);

      }else{
        this.$message.error(res&&res.msg)
        this.qrLoading=false
        setTimeout(() => {
          this.loading2=false
        }, 500);
      }
      this.loading2=false
    },
    onCancel(){
      this.dialogQr=false
      this.dataPicker=''
      this.timePicker=''
      this.input=''
    },
    // 获取列表
    getGrade() {
      this.loading=true
      getGrade({ pageSize: 10, pageNum: 1 }).then((res) => {
        this.loading=false
        this.total = res.total;
        this.tableData.forEach((item, index) => {
          this.tableData[index].gradeId = res.rows[index].gradeId;
          this.tableData[index].desiredGrowthValue =res.rows[index].gradeGrowValue;
          this.tableData[index].gradeCode=res.rows[index].gradeCode
        });
      });
    },
    // 点击确定
    determinate(ruleForm) {
      this.$refs[ruleForm].validate((valid) => {
        if (valid) {
          this.dialogVisible = false;
          this.upGrade();
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    // 点击取消
    cancellation() {
      this.$refs["ruleForm"].clearValidate();
      this.form.desiredGrowthValue = "";
      this.dialogVisible = false;
    },

    //发送更改请求
    upGrade() {
      const data = {
        gradeId: this.row.gradeId,
        // gradeName: this.row.levelName, //"普卡", 等级名称
        gradeGrowValue: this.form.desiredGrowthValue, //所需成长值
        // gradeCode: this.row.level, //级别 1-一级，2-二级，3-三级，4-四级，5-五级
        //   enterpriseId:
        //     this.presentEnterprise && this.presentEnterprise.enterpriseId,
      };
      upGrade(data).then((res) => {
        this.getGrade();
        this.$message({
          message: `${res.msg}`,
          type: "success",
        });
      });
    },

    // 对话框退出
    handleClose(done) {
      this.$refs["ruleForm"].clearValidate();
      this.form.desiredGrowthValue = "";
      this.dialogVisible = false;
    },
    // 编辑输入框
    inputAmountPayable() {
      this.$refs.ruleForm.validateField(["desiredGrowthValue"]);
    },
    // 点击编辑
    handleClick(scope) {
      this.form.desiredGrowthValue = "";
      this.row = scope.row;
      this.dialogVisible = true;
      this.form.levelName = scope.row.levelName;

      this.minimum = this.tableData[scope.$index - 1];
      this.maximum = this.tableData[scope.$index + 1];
    },
    // 分页器
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
    },
    // 分页器
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
    },
  },
};
</script>
<style scoped lang="scss">
.title {
  &::before {
    content: "*";
    color: red;
    margin-right: 5px;
  }
}
::v-deep .el-drawer__header {
  border-bottom: 1px solid #111;
}
.setting_form {
  padding: 1rem;
  box-sizing: border-box;
}
.footer {
  box-sizing: border-box;
  text-align: center;
  padding-top: 10rem;
}
.nav {
  margin: 10px 0 20px 0;
}
.container-pagination {
  margin-top: 30px;
}
.container-dialog {
  margin-top: 10%;
}
.control-amountPayable input::-webkit-outer-spin-button,
.control-amountPayable input::-webkit-inner-spin-button {
  -webkit-appearance: none;
}
.control-amountPayable input[type="number"] {
  -moz-appearance: textfield;
}
.qr_content{
  display: flex;
  justify-content: space-between;
  .Vip_grade {
    padding-left: 20px;
    font-size: 22px;
    .input_day > span{
      margin: 10px;
      display: flex;
      align-items: center;
      font-size:14px;
      font-weight: normal;
      .el-input-number{ 
        margin: 0 10px;
      }
      .el-input{
        width: 120px;
        margin: 0 10px;
      }
    }
    .time_picker{
      margin-top: 20px;
    }
  }
  .qr_code{
    width: 250px;
    height: 300px;
    position: relative;
    .empty{ 
      width: 250px;
      line-height: 300px;
      text-align: center;
      font-size: 17px;
    }
    .acton_btn{
      position: absolute;
      bottom: 0;
      width: 100%;
      margin-top: 15px;
      display: flex;
      justify-content: space-between;
      align-items: center;
      button{
        padding: 7.5px 0;
        border: 1px solid #666;
        border-radius: 6px;
        width: 110px;
        margin-left: 10px;
      }
      button:last-child{
        padding: 7.5px 0;
        border: unset;
        background-color: #4783ff;
        color: #fff;
        margin-right: 10px;
      }
    }
  }
}
 .tip{
    margin-top: 20px;
    text-align: center;
  }

</style>
